<template>
  <div>
    <p>Percent: {{ percent.toFixed(2) }}%</p>
    <button @click="startTransition">Start Transition</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      percent: 0,
      animationFrame: null,
    };
  },
  methods: {
    //将percent的值在0.5秒内从0增加到100
    animate() {
      const elapsed = Date.now() - this.startTime;
      const progress = Math.min(elapsed / 500, 1); // 限制在0到1之间
      this.percent = progress * 100;

      if (progress < 1) {
        // 如果还没有到达100%，则继续下一帧
        this.animationFrame = requestAnimationFrame(this.animate);
      } else {
        // 否则，清除动画帧
        cancelAnimationFrame(this.animationFrame);
        this.animationFrame = null;
      }
    },
    //启动animate动画
    startTransition() {
      if (this.animationFrame) return; // 如果已经开始了，就不要再开始了

      this.startTime = Date.now();
      this.animate(); // 开始动画
    },
  },
  beforeDestroy() {
    // 在组件销毁前清除动画帧
    if (this.animationFrame) {
      cancelAnimationFrame(this.animationFrame);
      this.animationFrame = null;
    }
  },
};
</script>
